package org.lc.platform.mybatis.handler;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.lc.platform.base.domain.JwtUser;
import org.lc.platform.base.enums.BaseEntityEnum;
import org.lc.platform.boot.util.LcAuthUtils;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
 * 自动填充添加、修改时间
 **/
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入时的填充策略
     *
     * @param metaObject Clinton Begin
     */
    @Override
    public void insertFill(MetaObject metaObject) {

        Object creator = getFieldValByName(BaseEntityEnum.CREATOR.getEntity(), metaObject);
        JwtUser lcUser = LcAuthUtils.getCurrentUser();
        if (ObjUtil.isEmpty(creator) && ObjUtil.isNotNull(lcUser)) {
            setFieldValByName(BaseEntityEnum.CREATOR.getEntity(), lcUser.getUserId(), metaObject);
        }
        Object createTime = getFieldValByName(BaseEntityEnum.CREATE_TIME.getEntity(), metaObject);
        if (ObjUtil.isEmpty(createTime)) {
            setFieldValByName(BaseEntityEnum.CREATE_TIME.getEntity(), LocalDateTime.now(), metaObject);
        }
        Object updateTime = getFieldValByName(BaseEntityEnum.UPDATE_TIME.getEntity(), metaObject);
        if (ObjUtil.isEmpty(updateTime)) {
            setFieldValByName(BaseEntityEnum.UPDATE_TIME.getEntity(), LocalDateTime.now(), metaObject);
        }

    }

    /**
     * 更新时的填充策略
     *
     * @param metaObject Clinton Begin
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Object operator = getFieldValByName(BaseEntityEnum.OPERATOR.getEntity(), metaObject);
        JwtUser lcUser = LcAuthUtils.getCurrentUser();
        if (ObjUtil.isEmpty(operator) && ObjUtil.isNotNull(lcUser)) {
            setFieldValByName(BaseEntityEnum.OPERATOR.getEntity(), lcUser.getUserId(), metaObject);
        }
        Object updateTime = getFieldValByName(BaseEntityEnum.UPDATE_TIME.getEntity(), metaObject);
        if (ObjUtil.isEmpty(updateTime)) {
            setFieldValByName(BaseEntityEnum.UPDATE_TIME.getEntity(), LocalDateTime.now(), metaObject);
        }

    }
}
